package cz.tsystems.portablecheckin;

import java.io.UnsupportedEncodingException;

import cz.tsystems.communications.CommunicationService;
import cz.tsystems.data.DataProvider;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class LoginActivity extends Activity {
	
	private EditText login, password;
	private Button btnLogin;
	
    private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			Bundle extra = intent.getBundleExtra("requestData");
			String userId;
			
			if(extra.getString("ACTION").equalsIgnoreCase("Login"))
			{
				userId = DataProvider.getSharedDataProvider().getLogetUser().get("PERSONAL_ID").textValue();
				Log.d("BROADCAST", extra.getString("ACTION") + ", "+ userId);
				if(!userId.isEmpty())
					LoginDone();
			}
			else if(extra.getString("ACTION").equalsIgnoreCase("GetStaticData"))
			{
				if(!isDBUpToDate())
					//TODO zobrazit hlasku o chybnom updatnuti DB
					Log.d("UPDATE DB", "nepodarilo sa updatnut DB");
			}
		}
    };	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        login = (EditText) this.findViewById(R.id.txtLogin);
        password = (EditText) this.findViewById(R.id.txtPassword);
        btnLogin = (Button) this.findViewById(R.id.btnLogin);
        
        password.setOnEditorActionListener(new DoneOnEditorActionListener());        
    }
    
    @Override
    protected void onStart() {
    	// TODO Auto-generated method stub
    	super.onStart();
        IntentFilter filterSend = new IntentFilter();
        filterSend.addAction("recivedData");
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filterSend);    	
    }
    
    public void onLoginClicked(View target) {
		startGetLogin();
    }
    
    private void startGetLogin()
    {
		String loginStr = String.format("%s:%s", login.getText(), password.getText());
		byte[] data = null;

		try {
			data = loginStr.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
		DataProvider.getSharedDataProvider().setLogin(base64);
    	
		Intent msgIntent = new Intent(this, CommunicationService.class);
		msgIntent.putExtra("ACTIONURL", "database/userdata");
    	msgIntent.putExtra("ACTION", "Login");		
		this.startService(msgIntent);
    }
    
    private void LoginDone()
    {
		if(!isDBUpToDate())
			updateDB();
    }
    
    private boolean isDBUpToDate()
    {
    	String dbStructVersion = "5";
		
		String actualDBStructVersion = DataProvider.getSharedDataProvider().getTheDBProvider().getDBStrutVersion();
		if(actualDBStructVersion.equals("NO_RECORD") || !dbStructVersion.equalsIgnoreCase( actualDBStructVersion)) {
			// TODO show warning
			return false;
		}
		
		String dbVersion = DataProvider.getSharedDataProvider().getTheDBProvider().getDBVersion();
		if(dbVersion.equals("NO_RECORD"))
			return false;
		
		if(dbVersion.equalsIgnoreCase( DataProvider.getSharedDataProvider().getConfiguration().get("DB_VERSION").textValue())) {
			setResult(RESULT_OK);
			finish();		
		}
		else
			return false;
		
		
		return true;
    }
    
    private void updateDB()
    {
		Intent msgIntent = new Intent(this, CommunicationService.class);
	
		msgIntent.putExtra("ACTIONURL", "database/StaticData");
    	msgIntent.putExtra("ACTION", "GetStaticData");		
		this.startService(msgIntent);

//		msgIntent.putExtra("ACTIONURL", "silhouette/SFiles");
//    	msgIntent.putExtra("ACTION", "GetSilhouette");		
//		this.startService(msgIntent);
//		msgIntent.putExtra("ACTIONURL", "pchi/Banners");
//    	msgIntent.putExtra("ACTION", "GetBanners");		
//		this.startService(msgIntent);    	
    }
    
    @Override
    protected void onDestroy() {
      // Unregister since the activity is about to be closed.
    	LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    	super.onDestroy();
    }
    
    @Override
    protected void onStop() {
    	// TODO Auto-generated method stub
    	LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);    	
    	super.onStop();
    }
    
    class DoneOnEditorActionListener implements OnEditorActionListener {
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
            	if(password.getText().length() == 0)
            	{
            		password.requestFocus();
            		return false;
            	}
            	else if(login.getText().length() == 0)
            	{
            		login.requestFocus();
            		return false;
            	}
                InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                startGetLogin();
                return true;	
            }
			return false;
		}
    }   
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	// TODO Auto-generated method stub
        switch(keyCode)
        {
            case KeyEvent.KEYCODE_BACK:
            	moveTaskToBack(true);
                return true;
        }
        return super.onKeyDown(keyCode, event);    	
    }
}
